import React from 'react';
import { router } from 'dva';
import { EnvConfig } from 'Configs';
import a2dmah5 from 'a2dmah5';
import LeftRightLayout from './layouts';
import NoLayout from './layouts/noLayout/index';
import Login from './routes/login';
import RoutePages from './routes/index';

const pages = a2dmah5.getPages();

const { Router, Route, Switch } = router;
const wetRootPath = EnvConfig.getServiceUrl('WebRootPath')();

const getPath = (path) => (wetRootPath + path);

const renderRoute = (p, app) => {
  let path;
  if (typeof (p.path) === 'string') path = getPath(p.path);
  else path = p.path.map(m => getPath(m));

  if (p.pageLayoutName === 'nolayout') {
    return <Route path={path} key={p.id} exact component={(props) => {
      return <NoLayout>{React.createElement(p.component, { ...props, app })}</NoLayout>;
    }} />;
  }

  return <Route path={path} key={p.id} exact component={(props) => {
    return <LeftRightLayout {...props} app={app}>
      {React.createElement(p.component, { ...props, app })}
    </LeftRightLayout>;
  }} />;
};

export default ({ history, app }) => {
  return (
    <Router history={history}>
      <Switch>
        {pages.map(m => renderRoute(m, app))}
        {RoutePages.map(m => renderRoute(m, app))}
        <Route path={getPath("/login.html")} exact component={(props) => <Login {...props} app={app} />} />
      </Switch>
    </Router>
  );
};
